package study.datastructure.leetcode.javase.primary.mutithreads;/**
 * @program: datastructure
 * @author: lcy
 * @create: 2024-09-11 08:54
 */

import sun.awt.SunHints;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 2024/9/11,
 */

//reentrantLock 编程题
    /*【编程题】请用等待/唤醒机制编写一个程序，要求：

第一个线程：遍历
[1,1000] 中所有的数字，在遍历过程中，如果发现这个数字能同时被 2,3,5整除，立即 wait() 等待，让第二个线程进入。
 第二个线程：运行时，将一个计数器+1 然后唤醒等待的线程。 主线程：睡眠2 秒，
 让两个线程全部执行完毕，打印计数器的结果。*/
public class JuClient {
    private static final ReentrantLock lock = new ReentrantLock();
    private static final Condition condition = lock.newCondition();

    static  int number=0;
    static boolean isEnd=false;
    static boolean isNotify=false;
    public static void main(String[] args) throws InterruptedException {
        Thread thread1=new Thread(()->{
                lock.lock();
                int i=0;
                while (i<=1000){
                    if (i % 2 == 0 && i % 3 == 0 && i % 5 == 0) {
                        isNotify=true; //许可
                        System.out.println("number被 2 3 5整除");
                        System.out.println(i);
                        //lock.notify();
                        condition.signal();
                        try {
                            condition.await();
                            //lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    i++;
                }
                isEnd=true;
                //结束循环
                condition.signalAll();
                //lock.notifyAll(); //key to 唤醒没有关的线程
            lock.unlock();
            System.out.println("end");
        });


        Thread thread2=new Thread(()->{
            while (!isEnd){ //确保先执行完 否者又可能死循环
                try {
                    waitAndCount();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        long start=System.currentTimeMillis();
        thread1.start();
        thread2.start();
        Thread.sleep(2000);
        System.out.println("事件间隔耗时:"+(System.currentTimeMillis()-start)); //2005ms

        System.out.println("number是"+number);

    }

    private static void waitAndCount() throws InterruptedException {
        //synchronized (lock){
        lock.lock();
            while (!isEnd){
                if (isNotify){
                    System.out.println("加一");
                    number+=1;  //执行业务逻辑
                    isNotify=false; //给回许可
                }
                //lock.notify();
                //lock.wait();
                condition.signal();
                condition.await();
            }
        //}
        lock.unlock();
    }



}
